package tools

import (
	"fmt"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	"os"
	"path"
	"time"
)

// 日志文件路径和文件名
var (
	logFilePath = "./log/"
	logFileName = "system.log"
)

var Logger *logrus.Logger

//func init() {
//	Logger = logrus.New()
//	Logger.SetLevel(logrus.DebugLevel)
//
//	// 设置输出，标准输出控制台
//	w1 := os.Stdout
//	// 输出到日志文件
//	w2, _ := os.OpenFile("./log/logrus.log", os.O_CREATE|os.O_WRONLY|os.O_CREATE, 0666)
//	Logger.SetOutput(io.MultiWriter(w1, w2))
//	Logger.SetFormatter(&logrus.JSONFormatter{})
//}

func init() {
	// 初始化日志记录器
	Logger = logrus.New()

	// 设置日志级别为 Debug
	Logger.SetLevel(logrus.DebugLevel)

	// 设置输出到文件
	fileName := path.Join(logFilePath, logFileName)
	src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if err != nil {
		fmt.Println("err", err)
	}
	Logger.Out = src

	// 设置 rotatelogs，实现日志文件轮转
	logWriter, _ := rotatelogs.New(
		fileName+".%Y%m%d.log",
		rotatelogs.WithLinkName(fileName),
		rotatelogs.WithMaxAge(15*24*time.Hour),
		rotatelogs.WithRotationTime(24*time.Hour),
	)

	// 配置 lfshook，将不同日志级别的日志写入同一个文件
	writeMap := lfshook.WriterMap{
		logrus.InfoLevel:  logWriter,
		logrus.FatalLevel: logWriter,
		logrus.DebugLevel: logWriter,
		logrus.WarnLevel:  logWriter,
		logrus.ErrorLevel: logWriter,
		logrus.PanicLevel: logWriter,
	}

	// 添加 lfshook 到 Logger
	Logger.AddHook(lfshook.NewHook(writeMap, &logrus.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	}))
}
